package xcmg.device.web.abnormal;

import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import xcmg.device.dao.entity.company.CompanyInfoDO;
import xcmg.device.dao.mapper.CompanyInfoMapper;
import xcmg.device.infra.AuthCode;
import xcmg.device.infra.BasicController;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.annotation.ExternalApiRequest;
import xcmg.device.service.ExternalParamCheckService;
import xcmg.device.service.abnormal.AbnormalOutService;
import xcmg.device.service.audit.AbnormalOutAuditService;
import xcmg.device.service.crm.util.ActionResultUtil;
import xcmg.device.service.vo.ExternalParamCheckVO;
import xcmg.device.service.vo.FunctionResult;
import xcmg.device.service.vo.abnormal.AbnormalAddVO;
import xcmg.device.service.vo.abnormal.AbnormalOutDetailVO;
import xcmg.device.service.vo.abnormal.AbnormalOutVO;
import xcmg.device.service.vo.delivery.BusinessOrderAuditParamVO;
import xcmg.device.service.vo.delivery.ManualFinishVO;
import yb.ecp.fast.infra.annotation.FastMappingInfo;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;
import yb.ecp.fast.infra.infra.log.LogHelper;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/abnormalOut")
public class AbnormalOutController extends BasicController{

    @Resource
    private AbnormalOutService abnormalOutService;
    @Resource
    private AbnormalOutAuditService abnormalOutAuditService;
    @Resource
    private CompanyInfoMapper companyInfoMapper;
    @Resource
    private ExternalParamCheckService externalParamCheckService;

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ApiOperation(value = "非正常出库增加")
    @FastMappingInfo(needLogin = true,code = AuthCode.StockOut.UNUSUAL_OUT_ADD)
    public ActionResult add(@RequestBody AbnormalAddVO abnormalAddVO)throws Exception {
        if(abnormalAddVO == null){
            return actionResult(ErrorCode.IllegalArument);
        }
        abnormalAddVO.getHeaderInfo().setOrgId(getOrgId());
        abnormalAddVO.getHeaderInfo().setCreateId(getUserId());
        abnormalAddVO.getHeaderInfo().setCreateName(getUserName());
        ErrorCode ret=ErrorCode.Success;
        if(!StringUtils.isEmpty(abnormalAddVO.getHeaderInfo().getAbnormalNo())){
            ret=abnormalOutService.update(abnormalAddVO, getOrgId());
        }
        else {
            ret=abnormalOutService.save(abnormalAddVO);
        }
        return actionResult(ret);
    }
    @RequestMapping(value = "/remove",method = RequestMethod.POST)
    @ApiOperation(value = "非正常出库删除")
    @FastMappingInfo(needLogin = true,code = AuthCode.StockOut.UNUSUAL_OUT_DEL)
    public ActionResult remove(@RequestBody String[] ids)throws Exception {
        if(ids==null||ids.length==0){
            return actionResult(ErrorCode.IllegalArument);
        }
        ErrorCode ret=abnormalOutService.remove(Arrays.asList(ids), getOrgId());
        return actionResult(ret);
    }
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    @ApiOperation(value = "非正常出库更新")
    @FastMappingInfo(needLogin = true,code = AuthCode.StockOut.UNUSUAL_OUT_EDIT)
    public ActionResult update(@RequestBody AbnormalAddVO abnormalAddVO)throws Exception {
        if(abnormalAddVO.getHeaderInfo().getId() == null){
            return actionResult(ErrorCode.AbnormalOut);
        }
        return actionResult(abnormalOutService.update(abnormalAddVO, getOrgId()));
    }

    @RequestMapping(value = "/list",method = RequestMethod.POST)
    @ApiOperation(value = "非正常出库列表")
    @FastMappingInfo(needLogin = true)
    public ActionResult listDeliveryNote(@RequestBody SearchCommonVO<AbnormalOutVO> condition)throws Exception {
        AbnormalOutVO abnormalOutVO =condition.getFilters();
        if(abnormalOutVO == null){
            abnormalOutVO = new AbnormalOutVO();
        }
        abnormalOutVO.setOrgId(getOrgId());
        condition.setFilters(abnormalOutVO);
        PageCommonVO pageCommonVO= abnormalOutService.list(condition,getDeptId());
        return actionValueResult(pageCommonVO.getPageInfo());
    }

    @RequestMapping(value = "/item",method = RequestMethod.GET)
    @FastMappingInfo(needLogin = true)
    public ActionResult item(String id){
        if(StringUtils.isEmpty(id)){
            return actionResult(ErrorCode.IllegalArument);
        }
        return actionResult(ErrorCode.Success,abnormalOutService.item(id));
    }

    @RequestMapping(value = "/export",method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true,code = AuthCode.StockOut.UNUSUAL_OUT_EXPORT)
    @ApiOperation(value = "导出")
    public void export(String[] ids)throws Exception {
        abnormalOutService.export(Arrays.asList(ids));
    }

    @RequestMapping(value = "/exportAll",method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true,code = AuthCode.StockOut.UNUSUAL_OUT_EXPORT)
    @ApiOperation(value = "导出全部")
    public void exportAll(AbnormalOutVO condition)throws Exception {
        condition.setOrgId(getOrgId());
        abnormalOutService.exportAll(condition,getDeptId());
    }

    @ResponseBody
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    @ApiOperation("零件批量导入")
    @FastMappingInfo(needLogin = true)
    public ActionResult importExcel(HttpServletRequest request) throws Exception{
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile(multipartRequest.getFileNames().next());
        String fileName = file.getOriginalFilename();
        FunctionResult<String> result=new FunctionResult<>();
        if (!fileName.trim().endsWith(".xls")) {
            result.setCode(ErrorCode.ImportExcelEndWithXLS);
        } else {
            InputStream in = file.getInputStream();
            result= abnormalOutService.importExcel(in, request.getParameter("x-warehouseCode"), request.getParameter("x-areaCode"), getOrgId());
        }
        return actionResult(result.getCode(), result.getValue());
    }

    @RequestMapping(value = "/download",method = RequestMethod.POST)
    @ApiOperation("下载零件批量导入模板")
    @FastMappingInfo(needLogin = true)
    public void download() throws Exception {
        abnormalOutService.download();
    }

    @RequestMapping(value = "/manualFinish", method = RequestMethod.POST)
    @ApiOperation("强制完成单据")
    public ActionResult manualFinish(@RequestBody ManualFinishVO manualFinishVO) throws Exception
    {
        return actionResult(abnormalOutService.manualFinish(manualFinishVO.getBillNo(), manualFinishVO.getMaterialsNo(), getOrgId()));
    }

    /**
     * 对外提供添加接口
     *
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/addAbnormalOut", method = RequestMethod.POST)
    public ActionResult addAbnormalOut(@RequestBody AbnormalAddVO model) throws Exception {
        LogHelper.monitor("addAbnormalOut接口入参：" + model.toString());
        ActionResult result;
        try {
            externalParamCheckService.checkParam(fillNeedCheckParan(model));
            CompanyInfoDO companyInfoDO = companyInfoMapper.itemBySap(model.getHeaderInfo().getSapCode());
            model.getHeaderInfo().setOrgId(companyInfoDO.getOrgId());
            result = abnormalOutService.save4CRM(model);
        } catch (Exception e) {
            return actionResult(ErrorCode.Failure, e.getMessage());
        }
        return result;
    }

    /**
     * 对外提供添加接口
     *
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/addAbnormalOutBySec", method = RequestMethod.POST)
    @ExternalApiRequest
    public ActionResult addAbnormalOutBySec(@RequestBody AbnormalAddVO model) throws Exception {
        LogHelper.monitor("addAbnormalOut接口入参：" + model.toString());
        ActionResult result;
        try {
            externalParamCheckService.checkParam(fillNeedCheckParan(model));
            CompanyInfoDO companyInfoDO = companyInfoMapper.itemBySap(model.getHeaderInfo().getSapCode());
            model.getHeaderInfo().setOrgId(companyInfoDO.getOrgId());
            result = abnormalOutService.save4CRM(model);
        } catch (Exception e) {
            return actionResult(ErrorCode.Failure, e.getMessage());
        }
        return result;
    }

    private ExternalParamCheckVO fillNeedCheckParan(AbnormalAddVO model) throws Exception {
        ExternalParamCheckVO param = new  ExternalParamCheckVO();
        if (CollectionUtils.isEmpty(model.getMaterialList())) {
            throw new Exception("缺少零件信息");
        }
        List<String> materialsNos = new ArrayList<>();
        for (AbnormalOutDetailVO detailVO : model.getMaterialList()) {
            materialsNos.add(detailVO.getMaterialsNo());
        }
        param.setMaterialsNos(materialsNos);
        AbnormalOutVO abnormalOut = model.getHeaderInfo();
        param.setSapCode(abnormalOut.getSapCode());
        param.setTypeId(abnormalOut.getTypeId());
        param.setAbnormalOutNo(abnormalOut.getAbnormalNo());
        param.setOutArea(abnormalOut.getOutArea());
        param.setOutLocation(abnormalOut.getOutLocation());
        param.setDeliveryTypeId(abnormalOut.getDeliveryTypeId());
        param.setSettleTypeId(abnormalOut.getSettleTypeId());
        return param;
    }


    /**
     * @Des 其它出库单审核通过
     * @Date 2021/4/14 16:14
     * @Author wangzhaoyu
     * @Param []
     * @Return yb.ecp.fast.infra.infra.ActionResult
     */
    @FastMappingInfo(needLogin = true)
    @RequestMapping(value = "/auditPass" , method = RequestMethod.POST)
    public ActionResult auditPass(@RequestBody BusinessOrderAuditParamVO param){
        String userId = getUserId();
        String userName = getUserName();
        try{
            ActionResult auditResult = abnormalOutAuditService.audit(param, userId, userName, true);
            return auditResult;
        }catch (Exception e){
            return ActionResultUtil.errorActionResult(ErrorCode.Failure.getCode(),e.getMessage());
        }
    }

    /**
     * @Des 其它出库单审核拒绝
     * @Date 2021/4/14 16:16
     * @Author wangzhaoyu
     * @Param [param]
     * @Return yb.ecp.fast.infra.infra.ActionResult
     */
    @FastMappingInfo(needLogin = true)
    @RequestMapping(value = "/auditReject" , method = RequestMethod.POST)
    public ActionResult auditReject(@RequestBody BusinessOrderAuditParamVO param){
        String userId = getUserId();
        String userName = getUserName();
        try{
            ActionResult actionResult = abnormalOutAuditService.audit(param, userId, userName, false);
            return actionResult;
        }catch (Exception e){
            return ActionResultUtil.errorActionResult(ErrorCode.Failure.getCode(),e.getMessage());
        }
    }

    /**
     * @Des 主页面数据看板--其它出库单待审核数据
     * @Date 2021/4/13 11:21
     * @Author wangzhaoyu
     * @Param []
     * @Return yb.ecp.fast.infra.infra.ActionResult
     */
    @RequestMapping(value = "/mainBoardWaitAudit" , method = RequestMethod.GET)
    @FastMappingInfo(needLogin = true)
    public ActionResult mainBoardWaitAudit() throws Exception {
        String orgId = getOrgId();
        //查询当前机构未删除，已提交的待审核数据
        Integer waitDataCount = abnormalOutService.countAuditData(orgId);
        return ActionResultUtil.successActionResult(waitDataCount);
    }
}
